package com.wl.springsecuritystudy;


import com.wl.springsecuritystudy.config.JwtAuthenticationToken;
import com.wl.springsecuritystudy.config.SessionInfo;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * 当前登录用户的上下文
 *
 * @author baizt
 */
public class LoginAccountContext {

    /**
     * 获取当前的用户ID
     *
     * @return
     */
    public static Optional<String> currentLoginUserId() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null) {
            return Optional.empty();
        }

        Object obj = authentication.getPrincipal();
        if (obj == null) {
            return Optional.empty();
        }

        return Optional.of(String.valueOf(obj));
    }

    /**
     * 获取当前的Session
     *
     * @return
     */
    public static Optional<SessionInfo> currentSession() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication instanceof JwtAuthenticationToken) {
            JwtAuthenticationToken authenticationToken = (JwtAuthenticationToken) authentication;
            return Optional.of(authenticationToken.getSession());
        }

        return Optional.empty();

    }












}
